package com.dankegongyu.sensors;

import android.content.Context;
import android.text.TextUtils;
import android.webkit.WebView;

import com.sensorsdata.analytics.android.sdk.SensorsDataAPI;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class DKSensorsUtil implements DKISensors {

    private static DKSensorsUtil instance;

    private DKSensorsUtil() {
    }

    public static DKSensorsUtil getInstance() {
        if (instance == null) {
            synchronized (DKSensorsUtil.class) {
                if (instance == null) {
                    instance = new DKSensorsUtil();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化sdk
     *
     * @param isDebug     是否是debug模式
     * @param context     上下文对象
     * @param serverUrl   上报服务器地址
     * @param isAutoTrack 是否开启自动统计
     */
    @Override
    public void init(boolean isDebug, Context context, String serverUrl, boolean isAutoTrack) {
        /**
         * Sensors Analytics DEBUG 模式
         * SensorsDataAPI.DebugMode.DEBUG_OFF - 关闭 Debug 模式
         * SensorsDataAPI.DebugMode.DEBUG_ONLY - 打开 Debug 模式，校验数据，但不进行数据导入
         * SensorsDataAPI.DebugMode.DEBUG_AND_TRACK - 打开 Debug 模式，校验数据，并将数据导入到 Sensors Analytics 中
         * 注意！请不要在正式发布的 App 中使用 Debug 模式！
         */
        SensorsDataAPI.DebugMode debugMode = isDebug
                ? SensorsDataAPI.DebugMode.DEBUG_AND_TRACK
                : SensorsDataAPI.DebugMode.DEBUG_OFF;
        SensorsDataAPI.sharedInstance(
                context,
                serverUrl,
                debugMode);
        if (isDebug) {
            configureSensors(10, 10 * 1000);
        } else {
            configureSensors(20, 60 * 1000);
        }
        SensorsDataAPI.sharedInstance().enableLog(isDebug);
        if (isAutoTrack) {
            setAutoTrack();
        }
    }

    /**
     * 打开自动采集, 并指定追踪哪些 AutoTrack 事件
     * https://www.sensorsdata.cn/manual/android_sdk_autotrack.html
     */
    public void setAutoTrack() {
        List<SensorsDataAPI.AutoTrackEventType> eventTypeList = new ArrayList<>();
        // $AppStart
        eventTypeList.add(SensorsDataAPI.AutoTrackEventType.APP_START);
        // $AppEnd
        eventTypeList.add(SensorsDataAPI.AutoTrackEventType.APP_END);
        // $AppViewScreen
        eventTypeList.add(SensorsDataAPI.AutoTrackEventType.APP_VIEW_SCREEN);
        // $AppClick
        eventTypeList.add(SensorsDataAPI.AutoTrackEventType.APP_CLICK);
        SensorsDataAPI.sharedInstance().enableAutoTrack(eventTypeList);
        // 开启Fragment页面浏览事件的自动采集 http://manual.sensorsdata.cn/sa/latest/page-1573983.html
        SensorsDataAPI.sharedInstance().trackFragmentAppViewScreen();
    }

    @Override
    public void setSuperProperties(Map<String, Object> properties) {
        SensorsDataAPI.sharedInstance().registerSuperProperties(getJsonObject(properties));
    }

    @Override
    public void unregisterSuperProperty(String propertyName) {
        SensorsDataAPI.sharedInstance().unregisterSuperProperty(propertyName);
    }

    @Override
    public void clearSuperProperties() {
        SensorsDataAPI.sharedInstance().clearSuperProperties();
    }

    @Override
    public void setUserInfo(Map<String, Object> properties) {
        SensorsDataAPI.sharedInstance().profileSet(getJsonObject(properties));
    }

    @Override
    public void trackInstallation(String eventName, Map<String, Object> properties) {
        SensorsDataAPI.sharedInstance().trackInstallation(eventName, getJsonObject(properties));
    }

    @Override
    public void onTrackEvent(String eventName, Map<String, Object> properties) {
        SensorsDataAPI.sharedInstance().track(eventName, getJsonObject(properties));
    }

    @Override
    public void onTrackWithoutParams(String eventName) {
        SensorsDataAPI.sharedInstance().track(eventName);
    }

    @Override
    public void trackAppViewScreen(String url, Map<String, Object> properties) {
        SensorsDataAPI.sharedInstance().trackViewScreen(url, getJsonObject(properties));
    }

    @Override
    public void login(String userId) {
        SensorsDataAPI.sharedInstance().login(userId);
    }

    @Override
    public void logout() {
        SensorsDataAPI.sharedInstance().logout();
    }

    @Override
    public void trackAppCrash() {
        SensorsDataAPI.sharedInstance().trackAppCrash();
    }

    @Override
    public void flush() {
        SensorsDataAPI.sharedInstance().flush();
    }

    @Override
    public void showUpWebView(Object webView, boolean isX5WebView) {
        if (webView == null) {
            return;
        }
        if (isX5WebView) {
            SensorsDataAPI.sharedInstance().showUpX5WebView(webView);
        } else {
            if (webView instanceof WebView) {
                SensorsDataAPI.sharedInstance().showUpWebView((WebView) webView, false);
            }
        }
    }

    /**
     * 修改 SDK 配置参数：
     * 默认为：100 / 15000 / 32*1024*1024
     * 也可以在Manifest中配置
     */
    @Override
    public void configureSensors(int bulkSize, int flushInterval) {
        SensorsDataAPI.sharedInstance().setFlushBulkSize(bulkSize);
        SensorsDataAPI.sharedInstance().setFlushInterval(flushInterval);
        //SensorsDataAPI.sharedInstance().setMaxCacheSize(maxCacheSize);
    }

    @Override
    public String getAnonymousId() {
        return SensorsDataAPI.sharedInstance().getAnonymousId();
    }

    @Override
    public void trackChannelEvent(String eventName) {
        SensorsDataAPI.sharedInstance().trackChannelEvent(eventName);
    }

    @Override
    public void trackChannelEvent(String eventName, Map<String, Object> properties) {
        SensorsDataAPI.sharedInstance().trackChannelEvent(eventName, getJsonObject(properties));
    }

    @Override
    public void ignoreAutoTrackActivities(List<Class<?>> activityList) {
        SensorsDataAPI.sharedInstance().ignoreAutoTrackActivities(activityList);
    }

    @Override
    public void ignoreAutoTrackActivity(Class<?> activity) {
        SensorsDataAPI.sharedInstance().ignoreAutoTrackActivity(activity);
    }

    @Override
    public void ignoreAutoTrackFragments(List<Class<?>> fragmentList) {
        SensorsDataAPI.sharedInstance().ignoreAutoTrackFragments(fragmentList);
    }

    @Override
    public void ignoreAutoTrackFragment(Class<?> fragment) {
        SensorsDataAPI.sharedInstance().ignoreAutoTrackFragment(fragment);
    }

    private JSONObject getJsonObject(Map<String, Object> map) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(map);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 埋点页面url
     */
    public static String getPageUrl(DKScreenAutoTracker dkScreenAutoTracker) {
        if (dkScreenAutoTracker != null && !TextUtils.isEmpty(dkScreenAutoTracker.trackPageUrl())) {
            return dkScreenAutoTracker.trackPageUrl();
//            return "${RouterConstants.SCHEME}://${RouterConstants.HOST}${getPageUrl()}"
        }
        return null; // 默认必须为null，不能""，具体原因看神策源码SensorsDataUtils.getScreenUrl()
    }

    /**
     * 处理{@link DKScreenAutoTracker}中的参数
     */
    public static JSONObject getJsonProperties(DKScreenAutoTracker dkScreenAutoTracker) {
        JSONObject jsonObject = new JSONObject();
        if (dkScreenAutoTracker != null) {
            try {
                // 标题
                String screenTitle = dkScreenAutoTracker.trackPageTitle();
                if (!TextUtils.isEmpty(screenTitle)) {
                    jsonObject.put("$title", screenTitle);
                }
                // 参数
                Map<String, Object> properties = dkScreenAutoTracker.trackProperties();
                if (properties != null && !properties.isEmpty()) {
                    for (Map.Entry<String, Object> entry : properties.entrySet()) {
                        String key = entry.getKey();
                        Object value = entry.getValue();
                        if (!TextUtils.isEmpty(key) && value != null) {
                            jsonObject.put(key, value);
                        }
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    public static void track(String eventName, Map<String, Object> params) {
        if (TextUtils.isEmpty(eventName)) {
            return;
        }
        // 根据eventName区分埋点事件类型
        eventName = eventName.trim();

        try {
            // 删除value为空的元素
            Iterator<Map.Entry<String, Object>> it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                if (entry == null || entry.getValue() == null) {
                    it.remove();
                }
            }
        } catch (Throwable e) {
//            e.printStackTrace();
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(params);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        SensorsDataAPI.sharedInstance().track(eventName, jsonObject);
    }
}
